const CryptoJS = require("crypto-js");

const axios = require('axios');
  



// const adc = 'ee6c0bfc79e0d22d88e08fdbbd0fcafa';
async function BreakerSwitch(accessToken1,status){
    

    // 加载.env文件  
      

    // 现在你可以通过process.env来访问环境变量  
    var timestamp = getTime();
   

    const clientId = 'rap5yyd478qnpywrd8df';
    const secret = 'f370771495cc4c66951b818c328cf19b';
    const accessToken = accessToken1;
    // var accessToken = "";  
    // if (process.env.hasOwnProperty("EASY_ACCESS_TOKEN") && process.env.EASY_ACCESS_TOKEN) {  
    //     accessToken = process.env.EASY_ACCESS_TOKEN;  
    // }

    const httpMethod = 'POST';
    const query = [  
        
      ];  
      
    
    
    // sha256
    
    var signMap = stringToSign(query,httpMethod,status)

    var signStr = signMap["signUrl"]
   
    var nonce = ""
    var sign = calcSign(clientId,accessToken, timestamp, nonce, signStr, secret);
   
    

const tokenheaders = {  
    'sign_method': 'HMAC-SHA256',  
    'client_id': 'rap5yyd478qnpywrd8df',  
    't': timestamp,  
    'mode': 'cors',  
    'Content-Type': 'application/json',  
    'sign': sign,  
    'access_token':accessToken1,
  };  
  const Body  = {
    "commands": [
      {
        "code": "switch",
        "value": !status
      }
    ]
  };

  try {
    const response = await axios.post('https://openapi.tuyacn.com/v1.0/devices/6cd2bd75ba8a2e86f98jrt/commands' , Body , {
      headers: tokenheaders
    });
    console.log('Command sent successfully:', response.data);
    return response.data;
  } catch (error) {
    console.error("发生错误:", error);
    throw error;
  }
}

module.exports = { BreakerSwitch };
function getTime(){
    var timestamp = new Date().getTime();
    return timestamp;
}

// 令牌验签计算
// function calcSign(clientId,timestamp,nonce,signStr,secret){
//     var str = clientId +timestamp + nonce + signStr;
//     console.log("str:",str);
//     var hash = CryptoJS.HmacSHA256(str, secret);
//     var hashInBase64 = hash.toString();
//     var signUp = hashInBase64.toUpperCase();
//     console.log("sign:",signUp)
//     console.log("t:",timestamp)
//     return signUp;
// }

// 业务验签计算
function calcSign(clientId,accessToken,timestamp,nonce,signStr,secret){
 
  var str = clientId + accessToken +timestamp + nonce + signStr;
  var hash = CryptoJS.HmacSHA256(str, secret);
  var hashInBase64 = hash.toString();
  var signUp = hashInBase64.toUpperCase();

  
  return signUp;
}




// 生成签名字符串
function stringToSign(query,method,status){
    var sha256 = "";
    var url = "";
    var headersStr = ""
    
    var map = {}
    var arr = []
    
    if(query){
        toJsonObj(query, arr, map)
    }
    let body = {
      "commands": [
        {
          "code": "switch",
          "value": !status
        }
      ]
    }
      
    // 将JSON对象转换为字符串  
    let jsonString = JSON.stringify(body);  
      
    // 计算SHA-256哈希值  
    sha256 = CryptoJS.SHA256(jsonString).toString(); 
    arr = arr.sort()
    arr.forEach(function(item){
            url += item + "=" + map[item] + "&"
    })
    if (url.length > 0 ) {
        url = url.substring(0, url.length-1)
        url = "/" + "v1.0/devices/6cd2bd75ba8a2e86f98jrt/commands" + "?" + url
    } else {
        url = "/" + "v1.0/devices/6cd2bd75ba8a2e86f98jrt/commands"
    }
    
    
    

    map["signUrl"] = method + "\n" + sha256 + "\n" + headersStr + "\n" + url
   
    map["url"] = url
    
    return map
}



// function replacePostmanParams(str){
//   while(str.indexOf("{{")!=-1&&str.indexOf("}}")!=-1){
//       const key = str.substring(str.indexOf("{{")+2,str.indexOf("}}"))
//       var value = '6cd2bd75ba8a2e86f98jrt'
//       if(!value) value=""
//       str = str.replace("{{"+key+"}}", value)
//   }
//   return str
// }



// function replacePostmanUrl(str){
 
//   while(str.indexOf("{{")!=-1&&str.indexOf("}}")!=-1){
//       const key = str.substring(str.indexOf("{{")+2,str.indexOf("}}"))
//       var value = '6cd2bd75ba8a2e86f98jrt'
//       if(!value) value=""
//       str = str.replace("{{"+key+"}}", value)
//   }

//   while(str.indexOf(":")!=-1){
//       const tempStr = str.substring(str.indexOf(":")+1,str.length);
//       var key = "";
//       if(tempStr.indexOf("/")!=-1){
//           key = tempStr.substring(0,tempStr.indexOf("/"))
//       }else if(tempStr.indexOf("?")!=-1){
//           key = tempStr.substring(0,tempStr.indexOf("?"))
//       }else {
//           key = tempStr.substring(0,tempStr.length)
//       }
      
//       if(!value) value=""
//       str = str.replace(":"+key, value)
//   }
//   return str
// }

function toJsonObj(params, arr, map){
  var jsonBodyStr = JSON.stringify(params)
  var jsonBody = JSON.parse(jsonBodyStr)
  jsonBody.forEach(function(item){
      if(!item.disabled){
          arr.push(item.key)
          map[item.key] = item.value
      }
  })
}
